<!-- 店铺管理页面 -->
<!--店铺管理页 StoreView.vue-->
<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">店铺管理</span>
    <el-button type="primary" style="float:right;margin-top:13px;" @click="beforeAddBusiness">新建门店</el-button>
  </div>
  <!-- 店铺查询卡片 -->
  <el-card style="margin:20px;height: 140px;">
    <el-form :inline="true">
      <el-form-item label="门店名称">
        <el-input placeholder="请输入" style="width:300px;"
                  v-model="SearchForm.storeName" ></el-input>
      </el-form-item>
      <el-form-item label="负责人联系方式">
        <el-input placeholder="请输入联系方式" style="width:300px;"
                  v-model="SearchForm.storeHeadPhone" ></el-input>
      </el-form-item>
      <el-form-item label="所属区域">
        <el-select  placeholder="请选择查询的省/市/区县" style="width:300px;">
          <el-option v-for="item in addressList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
      <el-form :inline="true">
        <el-form-item label="入驻日期" style="width:290px;">
          <el-date-picker
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              v-model="times"
              @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="门店状态" style="width:300px;">
        <el-select placeholder="请选择" v-model="SearchForm.storeStatus" @change="loadSearch">
          <el-option label="启用" value="0"/>
          <el-option label="禁用" value="1"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadGeoTableDataBypage">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 店铺列表表格数据 type="index"序号-->
  <el-card style="margin:20px;">
    <h3>店铺列表</h3>
    <el-table stripe :data="geoTableData">
      <el-table-column label="编号" prop="id" type="index" align="center" width="100"></el-table-column>
      <el-table-column label="门店名称" prop="storeName" align="center"></el-table-column>
      <el-table-column label="商家地址" prop="storeLocation" align="center"></el-table-column>
      <el-table-column label="门店电话" prop="storePhone" align="center"></el-table-column>
      <el-table-column label="负责人" prop="storeHeadName" align="center"></el-table-column>
      <el-table-column label="联系电话" prop="storeHeadPhone" align="center"></el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime" align="center"></el-table-column>
<!--      <el-table-column label="启用状态" prop="storeStatus" align="center">-->
<!--&lt;!&ndash;        <template #default="scope">&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;          <el-switch&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;              v-model="scope.row.status"&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;              @change="() => !isInitializing && changeStatus(scope.row.id, scope.row.status)"&ndash;&gt;&ndash;&gt;-->
<!--&lt;!&ndash;&lt;!&ndash;          />&ndash;&gt;&ndash;&gt;-->

<!--&lt;!&ndash;          <el-switch inactive-value="0" active-value="1" v-model="scope.row.status"&ndash;&gt;-->
<!--&lt;!&ndash;                     @change="() => !isInitializing && changeStatus(scope.row.id, scope.row.status)"></el-switch>&ndash;&gt;-->
<!--&lt;!&ndash;        </template>&ndash;&gt;-->
<!--        <template #default="scope">-->
<!--          <el-switch active-value="0" inactive-value="1" v-model="scope.row.status"-->
<!--                     @change="changeStatus(scope.row.id, scope.row.status)"></el-switch>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="status" label="用户状态" align="center">
        <template #default="scope">
          <el-switch :active-value="1" :inactive-value="0" v-model="scope.row.status" @change="changeStatus(scope.row.id, scope.row.status)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="updateStore(scope.row.id)">编辑</el-button>
          <el-button type="primary" link @click="deleteStore(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 新建门店弹窗 -->
  <el-dialog title="新建门店" v-model="DialogVisible" style="padding:40px;">
   <el-form  :label-width="'120px'" label-position="right">
     <el-form-item label="商家名称">
       <el-select v-model="newStoreForm.businessId" placeholder="请选择商家" style="width:300px;" clearable>
         <el-option label="请选择" :value="null"></el-option>
         <el-option
             v-for="item in storeFamilyList"
             :key="item.value"
             :label="item.label"
             :value="item.value">
         </el-option>
       </el-select>
     </el-form-item>
      <el-form-item label="门店名称">
        <el-input placeholder="请输入门店名称" style="width:300px;"
                  v-model="newStoreForm.storeName" ></el-input>
      </el-form-item>

      <el-form-item label="门店电话">
        <el-input placeholder="请输入门店电话" style="width:300px;"
                  v-model="newStoreForm.storePhone" ></el-input>
      </el-form-item>
      <el-form-item label=" 负责人">
        <el-input placeholder="请输入负责人" style="width:300px;"
                  v-model="newStoreForm.storeHeadName" ></el-input>
      </el-form-item>
      <el-form-item label="负责人电话">
        <el-input placeholder="请输入负责人电话" style="width:300px;"
                  v-model="newStoreForm.storeHeadPhone" ></el-input>
      </el-form-item>

        <el-form-item label="门店地区">
          <el-select   v-model="provinceId" placeholder="省" style="width:150px;" @change="handleProvinceChange">
            <el-option v-for="item in provinceList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>

          <el-select  v-model="cityId" placeholder="市" style="width:150px;" @change="handleCityChange" >
            <el-option v-for="item in cityList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>

<!--          <el-select v-model="areaId" placeholder="区" style="width:150px;">-->
<!--            <el-option v-for="item in areaList" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
<!--          </el-select>-->
        </el-form-item>
      <el-form-item label="详细店址">
        <el-input placeholder="请输入详细地址" style="width:300px;"
                  v-model="newStoreForm.storeLocation" ></el-input>
      </el-form-item>

        <el-form-item label="门店坐标">
          <!-- 地图容器 -->
          <div id="mapContainer" style="width:100%;height:50vh;"></div>
        </el-form-item>

        <!-- 坐标输入框（可选） -->
        <el-form-item label="经度">
          <el-input v-model="newStorelocation.longitude" placeholder="自动填充" disabled></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="newStorelocation.latitude" placeholder="自动填充" disabled></el-input>
        </el-form-item>
<!--     <el-form-item label="门店照片" prop="photo">-->
<!--       <el-row :gutter="30">-->
<!--         <el-col :span="12">-->
<!--           <el-upload-->
<!--               :file-list="photoFileList"-->
<!--               :action="actionUrl"-->
<!--               name="file"-->
<!--               list-type="picture-card"-->
<!--               :limit="1"-->
<!--               :on-preview="handlePictureCardPreview"-->
<!--               :on-remove="handleRemovePhoto"-->
<!--               :before-upload="validateImage"-->
<!--               @update:file-list="val => photoFileList = val"-->
<!--               :http-request="uploadPhoto"-->
<!--           >-->
<!--             <el-icon><el-button>上传图片</el-button></el-icon>-->
<!--           </el-upload>-->
<!--           <el-dialog v-model="dialogVisible">-->
<!--             <img w-full :src="dialogImageUrl" />-->
<!--           </el-dialog>-->
<!--         </el-col>-->
<!--       </el-row>-->
<!--     </el-form-item>-->

<!--     <el-form-item label="门店logo" prop="logo">-->
<!--       <el-row :gutter="30">-->
<!--         <el-col :span="12">-->
<!--           <el-upload-->
<!--               :file-list="logoFileList"-->
<!--               :action="actionUrl"-->
<!--               name="file"-->
<!--               list-type="picture-card"-->
<!--               :limit="1"-->
<!--               :on-preview="handlePictureCardPreview"-->
<!--               :on-remove="handleRemoveLogo"-->
<!--               :before-upload="validateImage"-->
<!--               @update:file-list="val => logoFileList = val"-->
<!--               :http-request="uploadLogo"-->
<!--           >-->
<!--             <el-icon><el-button>上传图片</el-button></el-icon>-->
<!--           </el-upload>-->
<!--         </el-col>-->
<!--       </el-row>-->
<!--     </el-form-item>-->


     <el-form-item label="商家简介" >
        <el-input placeholder="请输入商家简介" style="width:300px"
                  v-model="newStoreForm.storeIntroduction" ></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-select v-model="newStoreForm.sort" style="width:300px" placeholder="请选择" class="select-width-300">
          <el-option label="升序" value="0"></el-option>
          <el-option label="降序" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="营业时间">
        <el-input placeholder="请输入营业时间" style="width:300px;"
                  v-model="newStoreForm.tradeTime" ></el-input>
      </el-form-item>
      <el-form-item label="门店状态">
        <el-radio-group  v-model="newStoreForm.status">
          <el-radio  label="开启" value="1" ></el-radio>
          <el-radio  label="禁用" value="0"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveStore">确定</el-button>
        <el-button @click="resetStore">重置</el-button>
      </el-form-item>
   </el-form>
  </el-dialog>
  <div style="display: flex; justify-content: flex-end; margin: 20px;">
    <el-pagination
        background
        layout="prev, pager, next"
        :total="100"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
    />
  </div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {nextTick} from "vue";
import { DrawScene, DrawControl,OperateEventType } from 'bmap-draw';
onMounted(()=>{
  loadGeoTableDataBypage();
})
const newStorelocation=ref({
  longitude: '',
  latitude: ''
});
// -----------------------------------------


// 加载地图方法


// -----------------------------------------
const beforeAddBusiness=()=>{
  DialogVisible.value = true;
  // 发送请求获取省份列表
  loadCityList(); // 确保省份已加载
  loadgeo()
}
//7.准备一个电子围栏对象用于给后端发送新增请求时传递参数
const geofence = ref({
  name:'',//围栏名称
  position:{}//围栏位置数据,注意:它也是一个对象!
});
const loadgeo=  ()=> {
//一进到页面立即加载地图
    //表示DOM更新完毕后立即执行的方法,因为我们要确保上方的地图容器div已创建,才能往div里装地图
  nextTick(()=>{
    //创建地图实例,注意:忽略导入语句!不需要导入!
    let map = new BMapGL.Map("mapContainer");
    //设置地图展示的中心点,此处的坐标是天安门的经纬度
    let point = new BMapGL.Point(112.549248, 37.857014);
    //设置地图对象的中心点与缩放级别
    map.centerAndZoom(point, 15);


      //5.添加鼠标绘制控件
      //5.1 创建绘制场景类,这是其他绘制控件的基类,负责获取覆盖物,事件监听等,注意:需要导入!
      const scene = new DrawScene(map);
      //5.2 创建绘制控件对象,它的构造方法需要传入上面的绘制场景,并对它自己进行配置.注意:需要导入!
      const drawContrl = new DrawControl(scene, {
        //5.3 绘制控件自己的配置项:不显示图标提示 + 显示在容器右上角 + 显示圆形与矩形绘制按钮
        enableTips: false,
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        drawingItems: [
          'circle',
        ]
      });
      //6.监听绘制完成事件,获取触发完成事件的目标对象,注意需要导入OperateEventType!
      scene.addEventListener(OperateEventType.COMPLETE, (event) => {
        //event是完成事件的返回值,DOM中的所有事件对象都基于Event对象
        //event.target 用于获取当前触发完成事件的元素
        console.log(event.target);

        //8.1 获取触发完成事件目标对象的围栏覆盖物overlay
        let overlay = event.target.overlay;
        //8.2 判断当前的形状是圆形还是矩形
        //instanceof用来判断对象overlay是否为BMapGL.Circle类的实例
        if(overlay instanceof BMapGL.Circle){
          //8.3 设置圆形围栏的属性值
          geofence.value.position.type = 'circle';//设置围栏类型为圆形
          geofence.value.position.longitude = overlay.getCenter().lng;//设置圆心经度
          geofence.value.position.latitude = overlay.getCenter().lat;//设置圆心纬度
          geofence.value.position.radius = overlay.getRadius();//设置半径
          console.log(geofence.value);//{name: '', position: {…}}
          // 1. 将 geofence 的经纬度赋值给 newStorelocation
          newStorelocation.value.longitude = geofence.value.position.longitude;
          newStorelocation.value.latitude = geofence.value.position.latitude;
        }

      });
      //5.4 将准备好的绘制控件添加到地图上
      map.addControl(drawContrl);
    })

  }
// -------------------------------------------
const provinceList = ref([]); // 省份列表
const cityList = ref([]);    // 城市列表
const areaList = ref([]);    // 区县列表
const  provinceId=  ref(null);
const cityId = ref(null);
const areaId = ref(null);
// 表单中绑定的字段
const newStoreForm = ref({
  businessId: null,
  storeName: '',
  storePhone: '',
  storeHeadName: '',
  storeHeadPhone: '',
  provinceId: 1,
  cityId: 1,
  areaId: 1,
  storeLocation: '',
  latitude:'',
  storeLatitude:'',
  storeLongitude: '',
  storeImagesIds: [],
  storeLogo: '',
  storeIntroduction: '',
  sort: null,
  tradeTime: '',
  storeStatus: null

});

// 获取城市列表
const loadCityList = () => {
  axios.get(BASE_URL+'3030/admin/basic/area/queryList')
      .then(res => {
        console.log(res.data)
        if (res.data.code === '0') {
          // provinceList.value = res.data.data;
          // 将原始数据的 id 映射为 value，name 映射为 label
          provinceList.value = res.data.data.map(item => ({
            label: item.name,
            value: item.id
          }));
          console.log(provinceList.value)
        }else{
          ElMessage.error("请求错误",res.data.msg);
        }
      });
};

// 获取区县列表
const loadAreaList = (parentId) => {
  console.log('获取区县列表', parentId)
  axios.get(BASE_URL+'3030/admin/basic/area/'+parentId)
      .then(res => {
        console.log(res.data.data)
        if (res.data.code === '0') {
          // areaList.value = res.data.data;
          // 将原始数据的 id 映射为 value，name 映射为 label
          cityList.value = res.data.data.map(item => ({
            label: item.name,
            value: item.id
          }));
          console.log("市区信息",cityList.value)
          newStoreForm.value.areaId = null;
        }
      });
};

// 省份选择变化
const handleProvinceChange = (provinceId1) => {
  console.log('省份选择变化', provinceId1)
  newStoreForm.value.provinceId = provinceId1;
  newStoreForm.value.cityId = null;
  newStoreForm.value.areaId = null;
  if (provinceId1) {
    loadAreaList(provinceId1);
  }
};

// 城市选择变化
  const handleCityChange = (cityId) => {
//   console.log('城市选择变化', cityId)
//   newStoreForm.value.cityId = cityId;
//   newStoreForm.value.areaId = null;
//   if (cityId) {
//     loadAreaList(cityId);
//   }
};

const photoFileList = ref([]);
const logoFileList = ref([]);
const dialogVisible = ref(false);
const dialogImageUrl = ref('');

const actionUrl = ref( BASE_URL+ '8080/v1/file/upload');

const validateImage = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
  const isValidSize = file.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片');
    return false;
  }

  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB');
    return false;
  }

  return true;
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

const handleRemovePhoto = (uploadFile, uploadFiles) => {
  // const imgUrl = uploadFile.response?.data;
  // if (imgUrl) {
  //   axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl).then((res) => {
  //     if (res.data.code === 2000) ElMessage.success('门店照片删除成功');
  //   });
  // }
  // photoFileList.value = uploadFiles;
};

const handleRemoveLogo = (uploadFile, uploadFiles) => {
  // const imgUrl = uploadFile.response?.data;
  // if (imgUrl) {
  //   axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl).then((res) => {
  //     if (res.data.code === 2000) ElMessage.success('门店LOGO删除成功');
  //   });
  // }
  // logoFileList.value = uploadFiles;
};

const uploadPhoto = ({ file }) => {
  const formData = new FormData();
  formData.append("file", file);
  console.log('file: ', file);
  axios.post(BASE_URL + '4040/admin/basic/store/saveStorePhoto', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    console.log("此为请求返回值",res.data.data);
    if (res.data.code === '0') {
      ElMessage.success('门店照片上传成功');
      newStoreForm.value.storeImagesIds.push(res.data.data.fileUuid); // 假设返回的是图片路径
    } else {
      ElMessage.error('门店照片上传失败');
    }
  }).catch(err => {
    ElMessage.error('上传出错，请重试');
    console.error(err);
  });
};

const uploadLogo = ({ file }) => {
  const formData = new FormData();
  formData.append("file", file);

  axios.post(BASE_URL + '4040/admin/basic/store/saveStorePhoto', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (res.data.code === '0') {
      ElMessage.success('门店LOGO上传成功');
      newStoreForm.value.storeLogo = res.data.data.url;
    } else {
      ElMessage.error('门店LOGO上传失败');
    }
  }).catch(err => {
    ElMessage.error('上传出错，请重试');
    console.error(err);
  });
};

// 新建门店弹窗状态
const DialogVisible = ref(false);
//点击 新建门店弹窗出现

//定义数组用来保存门店表格数据的入住时间
const times =ref([]);
const storeFamilyList = ref([
  { label: '东来顺', value: '12' },
  { label: '茶百道', value: '13' },
  { label: '肯德基', value: '14' },
  { label: '麦当劳', value: '15' }
]);
//改变时间
const handleDateChange = () => {
  if (times.value && times.value.length === 2) {
  SearchForm.value.startingTime = times.value[0];
  SearchForm.value.endTime= times.value[1];
  } else {
    SearchForm.value.startingTime = '';
    SearchForm.value.endTime = '';
  }
};

//定义搜索门店的表单数据
const SearchForm = ref({storeName:'',storePhone:'',storeHeadPhone:''
  ,storeStatus:'',startingTime:'', endTime:''})
const addressList=ref([]);

//定义数组用来保存店铺列表的表格数据
const geoTableData = ref([]);
//定义加载店铺列表的方法


//定义重置搜索的方法
const resetSearch = ()=>{
 SearchForm.value = {storeName:'',storePhone:'',storeHeadPhone:''
   ,storeStatus:'',startingTime:'', endTime:''};
  times.value = [];
  loadGeoTableDataBypage();
}
//定义数组用来保存新建门店弹窗的表单数据


//定义保存新建门店的方法
const saveStore = ()=>{
  newStoreForm.value.storeLatitude=''+newStorelocation.value.latitude;
  newStoreForm.value.storeLongitude=''+newStorelocation.value.longitude;
  console.log("最终传参",newStoreForm.value);
  axios.post(BASE_URL+'4040/admin/basic/store/add',newStoreForm.value)
      .then((response)=>{
    console.log(response.data)
    if(response.data.code=='0'){
      resetStore();
      ElMessage.success('保存成功!');
      DialogVisible.value = false;
      loadGeoTableDataBypage();
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}
const resetStore=()=>{
  newStoreForm.value = {
    businessId: null,
    storeName: '',
    storePhone: '',
    storeHeadName: '',
    storeHeadPhone: '',
    provinceId: 1,
    cityId: 1,
    areaId: 1,
    storeLocation: '',
    latitude:'',
    storeLatitude:'',
    storeLongitude: '',
    storeImagesIds: [],
    storeLogo: '',
    storeIntroduction: '',
    sort: null,
    tradeTime: '',
    storeStatus: null


  };
}
// //定义修改店铺列表的启用状态的方法
// const isInitializing = ref(false);
const changeStatus =(id,status)=>{
  // isInitializing.value=true;
  // console.log(typeof status, typeof id)
  // let data = qs.stringify({id:id,status:status});
  axios.post(BASE_URL+'4040/admin/basic/store/updateStatus/'+id+'/'+status)
      .then((response)=>{
    if(response.data.code ==='0'){
      ElMessage.success('状态修改成功!');
      console.log("前端"+id+"/"+status);
      // loadGeoTableDataBypage();
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//定义删除店铺的方法
const deleteStore = (id)=>{
  if(id==null){
    ElMessage.error('请重新选择要删除的店铺!');
    return;
  }
  if(confirm('您确认要删除本店铺吗?')){
    console.log(typeof id)
    axios.get(BASE_URL+'4040/admin/basic/store/delete/'+id).then((response)=>{
      if(response.data.code==='0'){
        ElMessage.success('删除成功!');
        loadGeoTableDataBypage();
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}
// 当前页码和每页数量
const currentPage = ref(1);
const pageSize = ref(10);

// 分页切换时触发
const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  loadGeoTableDataBypage();
};

// 修改 loadGeoTableData 方法，加上分页参数
const loadGeoTableDataBypage = () => {
  const params = {
    ...SearchForm.value,
    pageNo: currentPage.value,
    pageSize: pageSize.value
  };
  // 先设为 true，阻止 change 触发
  // isInitializing.value = true;
console.log(params);
  axios.post(BASE_URL + '4040/admin/basic/store/getAll', params).then((response) => {
    if (response.data.code ==='0'&&response.data.data.objects) {
      console.log(response.data.data.objects);
      ElMessage.success('请求成功!');
      geoTableData.value = response.data.data.objects.map(item => ({
        id: item.id,
        storeName: item.storeName,
        storeLocation: item.storeLocation,
        storePhone: item.storePhone,
        storeHeadName: item.storeHeadName,
        storeHeadPhone: item.storeHeadPhone,
        createTime: item.createTime,
        updateTime: item.updateTime,
        status: item.storeStatus
      }));
    } else {
      console.error('请求失败:', response.data);
      ElMessage.error('请求失败或数据不存在，请稍后再试');
    }
  }).catch(error => {
    console.error('请求失败数据不存在:', error);
    ElMessage.error('数据不存在，请稍后再试');
  }).finally(() => {
    // isInitializing.value = false; // 数据加载完成后再允许触发
  });
};


//定义编辑的方法
  const updateStore=(id)=>{
    ElMessage.success('业务有待开发');
  }

</script>



<style scoped>

</style>